﻿using Core.Framework;
using DotNetty.Framework;
using DotNetty.Framework.ExtendChannelOfClient;
using DotNetty.OrleansClient;
using DotNetty.Transport.Channels;
using Grain.Interfaces;
using iTool.ClusterComponent;
using Orleans;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace iTool.Connector
{
    public class JWTBindChannelInfo : IBindChannelInfo
    {
        iToolConnectorProvider iClient;

        //public string[] IgnoreClient { get; }

        public JWTBindChannelInfo(iToolConnectorProvider iClient)
        {
            this.iClient = iClient;
            //this.IgnoreClient = new string[] { "gateway.janjanle.com", "gateway.itool.store" };
        }

        public async Task BindClientAsync(IChannelHandlerContext context, ConnectorInfo channelClientInfo)
        {
            
            if (!string.IsNullOrWhiteSpace(channelClientInfo.UUID))
            {
                LoggerUtils.Write("channelClientInfo:" + channelClientInfo.TryToJson());
                context.BindClientUUID(channelClientInfo);
            }

            await Task.CompletedTask;
        }

        public async Task BindIdentityAsync(IChannelHandlerContext context, string token)
        {

            var jwt = new iToolJwtSecurity(AppSetting.iToolConfigure.JWTToken ?? "help-itool@qq.com");

            var claims = jwt.GetClaims(token);
            if (claims != null)
            {
                var channel = jwt.GetChannel(claims);

                // 检查是否存在Channel
                if (!string.IsNullOrWhiteSpace(channel))
                {
                    await this.BindChannel(context, channel);
                }
            }
        }

        private async Task BindChannel(IChannelHandlerContext context, string channel)
        {
            iToolClusterHostClient cluster = this.iClient.GetClusterClient();
            var iChannel = cluster.GetService<IChannelService>(channel);
            List<string> subscribes = await iChannel.GetSubscribes();

            subscribes.Remove(channel);

            // 给当前上下文绑定订阅信息
            foreach (var item in subscribes)
                context.Subscribe(item);

            context.BindChannel(channel);

            // 上线
            await iChannel.GoOnline(AppSetting.iToolConfigure.Ip);

        }

    }
}
